package com.hxd.otc.base;

import android.arch.lifecycle.Lifecycle;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.baidu.mobstat.StatService;
import com.hxd.otc.R;
import com.hxd.otc.dialog.LoadingDialog;
import com.hxd.otc.mvp.base.BasePresenter;
import com.hxd.otc.mvp.base.IBaseView;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StatusBarHelper;
import com.hxd.otc.widget.BlocksToast;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/5/31 11:19
 * 描  述 :  ${基类Activity}
 */
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IBaseView {

    private Unbinder mBind;
    private SystemBarTintManager mSystemBarTintManager;
    protected P mPresenter;
    protected LoadingDialog spinnerDlg;//等待框

    /**
     * 绑定布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化视图控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 做事件监听的初始化
     */
    protected abstract void initEvent();

    /**
     * @return
     */
    protected abstract P createPresenter();


    public void setFullWindows(boolean mIsFullWindows) {
        this.mIsFullWindows = mIsFullWindows;
    }

    private boolean mIsFullWindows;

    public boolean getImmersiveStatus() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getLayoutId());
        init();
        initPermissions();

    }

    protected void initPermissions() {
        mBind = ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
    }

    protected void init() {
        initWindows();
        mPresenter = createPresenter();
    }

    protected void initWindows() {
        Window window = getWindow();
        if (window == null)
            return;
        if (!mIsFullWindows) {
            if (!getImmersiveStatus()) {
                //设置沉浸式状态栏
                initStatusWindows(window);
            } else {
                //设置沉浸式窗口
                initImmersiveStatusWindows();
            }
        } else {
            //设置全屏
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    protected void initImmersiveStatusWindows() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    protected void initStatusWindows(@NonNull Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (mSystemBarTintManager == null) {
                mSystemBarTintManager = new SystemBarTintManager(this);
                mSystemBarTintManager.setStatusBarTintColor(ContextCompat.getColor(this, getStatusColor()));
                mSystemBarTintManager.setStatusBarTintEnabled(true);
            }
        }
    }

    protected void $startActivity(@NonNull Class clazz) {
        startActivity(new Intent(this, clazz));
    }

    protected void $startActivity(@NonNull Class clazz, boolean isFinish) {
        startActivity(new Intent(this, clazz));
        if (isFinish) {
            finish();
        }
    }

    protected void $startActivity(@NonNull Class clazz, @NonNull Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    protected void $startActivity(@NonNull Class clazz, @NonNull Bundle bundle, boolean isFinish) {
        $startActivity(clazz, bundle);
        if (isFinish) {
            finish();
        }
    }

    protected Bundle getBundle() {
        Intent intent = getIntent();
        if (intent == null) {
            return null;
        }
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return null;
        }
        return bundle;
    }

    protected void $startActivityForResult(@NonNull Class clazz, int requestCode) {
        startActivityForResult(new Intent(this, clazz), requestCode);
    }

    protected void $startActivityForResult(@NonNull Class clazz, @NonNull Bundle bundle, int request) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle == null ? new Bundle() : bundle);
        startActivityForResult(intent, request);
    }

    protected void $setResult(Intent intent, boolean isFinish) {
        setResult(RESULT_OK, intent);
        if (isFinish) {
            finish();
        }
    }

    protected void $setResult(boolean isFinish) {
        setResult(RESULT_OK);
        if (isFinish) {
            finish();
        }
    }

    protected void $setResult() {
        setResult(RESULT_OK);
    }

    @Override
    public <X> AutoDisposeConverter<X> bindAutoDispose() {

        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(this, Lifecycle.Event.ON_DESTROY));
    }

    /**
     * /订阅的事件立即被消费
     *
     * @param event
     */
    protected void post(Object event) {
        EventBus.getDefault().post(event);
    }

    /**
     * 当你希望你的事件不被马上处理的时候，举个栗子，比如说，在一个详情页点赞之后，产生一个VoteEvent，
     * VoteEvent并不立即被消费，而是等用户退出详情页回到商品列表之后，接收到该事件，
     * 然后刷新Adapter等。其实这就是之前我们用startActivityForResult和onActivityResult做的事情。
     *
     * @param event
     */
    protected void postSticky(Object event) {
        EventBus.getDefault().postSticky(event);
    }

    /**
     * 注册 EventBas EventBus  3.0 注册方式只有一个
     */
    public void registerEventBus() {
        EventBus.getDefault().register(this);
    }

    /**
     * 解除绑定
     */
    protected void unregisterEventBus() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        if (mBind != null) {
            mBind.unbind();
        }
        if (mPresenter != null) {
            mPresenter.destroy();
            this.mPresenter = null;
        }
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            unregisterEventBus();
        }
        dismissSpinnerDlg();
    }

    @Override
    public void showToast(@NonNull String toast) {
        BlocksToast.get().showToast(toast);
    }

    @Override
    public void onShowLoading() {

    }

    @Override
    public void onHideLoading() {

    }

    @Override
    public void onError(int code) {

    }

    /**
     * 显示加载对话框
     *
     * @param msg
     * @param isCancel
     */
    protected void showSpinnerDlg(String msg, boolean isCancel) {
        if (spinnerDlg == null) {
            spinnerDlg = new LoadingDialog(this);
        }
        spinnerDlg.setText(msg).setCancel(isCancel).show();
    }

    /**
     * 关闭加载对话框
     */
    protected void dismissSpinnerDlg() {
        if (spinnerDlg != null && spinnerDlg.isShowing()) {
            spinnerDlg.dismiss();
        }
    }

    protected int getStatusColor() {
        return android.R.color.white;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (!hasFocus) return;
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(StatusBarHelper.setStatusBarLightMode(getWindow()) ? Color.TRANSPARENT : ResourceUtil.getColor(R.color.color_StatusBarColor_ChangeFail));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 页面埋点，需要使用Activity的引用，以便代码能够统计到具体页面名
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 页面结束埋点，需要使用Activity的引用，以便代码能够统计到具体页面名
        StatService.onPause(this);
    }
}
